package BD;

import BE.Clavesnopermitidas;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Claves no permitidas pra los usuarios, se almacenan en claro
 *
 * @author marvil
 */
public class ClavesNoPermitidasBD {

    Transaction tx = null;
    private Session session = null;

    public boolean insertarClave(Clavesnopermitidas objClave) {
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            tx = session.beginTransaction();
            session.save(objClave);
            tx.commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
                if (tx != null && tx.isActive()) {
                tx.rollback();
            }
            return false;
        }
    }

    public boolean eliminarClave(Clavesnopermitidas objClave) {
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            tx = session.beginTransaction();
            session.delete(objClave);
            tx.commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
                if (tx != null && tx.isActive()) {
                tx.rollback();
            }
            return false;
        }
    }

    public List<Clavesnopermitidas> obtenerClaves() {
        List<Clavesnopermitidas> lista = new ArrayList<Clavesnopermitidas>();
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            tx = session.beginTransaction();
            String hql = "FROM Clavesnopermitidas as c";
            Query query = session.createQuery(hql);
            session.flush();
            lista = query.list();
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
                if (tx != null && tx.isActive()) {
                tx.rollback();
            }
        }
        return lista;
    }

    public Clavesnopermitidas obtenerClave(Clavesnopermitidas objClave) {
        List<Clavesnopermitidas> lista = new ArrayList<Clavesnopermitidas>();
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            tx = session.beginTransaction();
            String hql = "FROM Clavesnopermitidas as c WHERE c.cvValor = :strValor";
            String strValor = objClave.getCvValor();
            Query query = session.createQuery(hql);
            query.setString("strValor", strValor);
            session.flush();
            lista = query.list();
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
                if (tx != null && tx.isActive()) {
                tx.rollback();
            }
        }
        if (lista.size() == 1) return lista.get(0);
        else return null;
    }

}
